package org.huashui.interceptor;

import org.huashui.authentication.ParseAuthName;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @authorhuashui
 * @blog http://huashui.org
 */
@SuppressWarnings("serial")
public class AuthInterceptor extends AbstractInterceptor {

        @Override
        public String intercept(ActionInvocation invocation) throws Exception {
                ActionContext context = invocation.getInvocationContext();
                System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                String user = (String) context.getSession().get("user");
                String rights = (String) context.getSession().get("rights");
                if (null != user) {
                        ActionProxy proxy = invocation.getProxy();
                        String methodName = proxy.getMethod();
                        Object action = proxy.getAction();
                        String auth = null;
                        try {
                                auth = ParseAuthName.parseAuthentication(action.getClass(),
                                                methodName, null);

                        } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                                ActionContext.getContext().put("tip", "没有权限");
                                return Action.LOGIN;
                        }

                        if (null != auth) {
                                if ("TEST_AUTH".equals(auth)) {
                                        return invocation.invoke();
                                }
                        }
                        ActionContext.getContext().put("tip", "没有权限");
                        return Action.LOGIN;
                } else {
                        ActionContext.getContext().put("tip", "没有登录");
                        return Action.LOGIN;
                }

        }

}